package extras.mak001;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.rsbuddy.script.task.LoopTask;
import com.rsbuddy.script.util.Timer;

public class Ranker extends LoopTask {

	private Timer rankTime = new Timer(360000);
	private static int rank = 0;
	private boolean isStarting = true;
	private static String uname = "";
	private static String sname = "";

	@Override
	public int loop() {

		if (!uname.equals("") && !sname.equals("")) if (rankTime.getRemaining() == 0
				|| isStarting == true) {
			try {
				URL url;
				URLConnection urlConn;

				url = new URL("http://mak001.x10.mx/dynamicsig/getRank.php");

				urlConn = url.openConnection();
				urlConn.setRequestProperty("User-Agent", "| supersecret |");
				urlConn.setDoOutput(true);
				urlConn.setDoInput(true);
				urlConn.setUseCaches(false);
				urlConn.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				String content = "script=" + sname + "&rank=" + uname;
				DataOutputStream wr = new DataOutputStream(urlConn
						.getOutputStream());

				wr.writeBytes(content);
				String line;
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						urlConn.getInputStream()));
				while ((line = rd.readLine()) != null) {
					try {
						rank = Integer.parseInt(line.replace("<br />", ""));
					} catch (Exception e) {
						rank = 0;
					}
				}
				wr.flush();
				wr.close();
				rd.close();
				if (isStarting == true) {
					isStarting = false;
				}
				rankTime.reset();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// TODO Auto-generated method stub
		return 0;
	}

	public static int getRank() {

		return rank;
	}

	public static void setScript(String script, String user) {

		uname = user;
		sname = script;
	}

}
